<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>配置管理 - GitLab提交日志分析工具</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Noto Sans SC', sans-serif;
            background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
            min-height: 100vh;
        }
        .hero-title {
            font-family: 'Noto Serif SC', serif;
            background: linear-gradient(135deg, #2d3748, #4299e1);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        .glass-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        .config-card {
            transition: all 0.3s ease;
            border-left: 4px solid transparent;
        }
        .config-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            border-left-color: #4299e1;
        }
        .status-connected {
            background: linear-gradient(135deg, #48bb78, #38a169);
        }
        .status-disconnected {
            background: linear-gradient(135deg, #f56565, #e53e3e);
        }
        .status-pending {
            background: linear-gradient(135deg, #ed8936, #dd6b20);
        }
        .btn-primary {
            background: linear-gradient(135deg, #4299e1, #2b6cb0);
            transition: all 0.3s ease;
        }
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(66, 153, 225, 0.3);
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="fixed top-0 left-0 right-0 z-50 glass-card border-b">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center space-x-4">
                    <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg flex items-center justify-center">
                        <span class="text-white font-bold text-sm">GL</span>
                    </div>
                    <h1 class="text-xl font-bold text-gray-800">GitLab分析工具</h1>
                </div>
                <div class="flex space-x-6">
                    <a href="index.html" class="text-gray-600 hover:text-blue-600 transition-colors">控制台</a>
                    <a href="config.html" class="text-blue-600 font-medium border-b-2 border-blue-600 pb-1">配置管理</a>
                    <a href="reports.html" class="text-gray-600 hover:text-blue-600 transition-colors">报告中心</a>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <main class="pt-20 pb-12">
        <!-- 标题区域 -->
        <section class="relative overflow-hidden bg-gradient-to-br from-gray-50 to-blue-50 py-16">
            <div class="absolute inset-0 opacity-10">
                <img src="resources/config-bg.jpg" alt="背景" class="w-full h-full object-cover">
            </div>
            <div class="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="text-center">
                    <h2 class="hero-title text-4xl md:text-5xl font-bold mb-4">
                        配置管理中心
                    </h2>
                    <p class="text-xl text-gray-600 mb-8 max-w-3xl mx-auto">
                        管理您的GitLab仓库连接配置，支持多个项目和团队协作
                    </p>
                    <button onclick="showAddConfigModal()" class="btn-primary text-white font-bold py-3 px-8 rounded-xl text-lg shadow-lg">
                        ➕ 添加新配置
                    </button>
                </div>
            </div>
        </section>

        <!-- 配置列表 -->
        <section class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
            <div class="mb-8">
                <div class="flex justify-between items-center">
                    <h3 class="text-2xl font-bold text-gray-800">我的配置</h3>
                    <div class="flex items-center space-x-4">
                        <div class="flex items-center space-x-2">
                            <div class="w-3 h-3 bg-green-500 rounded-full"></div>
                            <span class="text-sm text-gray-600">已连接</span>
                        </div>
                        <div class="flex items-center space-x-2">
                            <div class="w-3 h-3 bg-orange-500 rounded-full"></div>
                            <span class="text-sm text-gray-600">待验证</span>
                        </div>
                        <div class="flex items-center space-x-2">
                            <div class="w-3 h-3 bg-red-500 rounded-full"></div>
                            <span class="text-sm text-gray-600">连接失败</span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="configGrid">
                <!-- 配置将通过JavaScript动态加载 -->
            </div>
        </section>

        <!-- 配置统计 -->
        <section class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
            <div class="glass-card rounded-2xl p-6 shadow-xl">
                <h3 class="text-xl font-bold text-gray-800 mb-6">配置统计</h3>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                    <div class="text-center p-4 bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl">
                        <div class="text-3xl font-bold text-blue-600 mb-2" id="totalCount">0</div>
                        <div class="text-sm text-blue-700">总配置数</div>
                    </div>
                    <div class="text-center p-4 bg-gradient-to-br from-green-50 to-green-100 rounded-xl">
                        <div class="text-3xl font-bold text-green-600 mb-2" id="connectedCount">0</div>
                        <div class="text-sm text-green-700">已连接</div>
                    </div>
                    <div class="text-center p-4 bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl">
                        <div class="text-3xl font-bold text-orange-600 mb-2" id="pendingCount">0</div>
                        <div class="text-sm text-orange-700">待验证</div>
                    </div>
                    <div class="text-center p-4 bg-gradient-to-br from-red-50 to-red-100 rounded-xl">
                        <div class="text-3xl font-bold text-red-600 mb-2" id="failedCount">0</div>
                        <div class="text-sm text-red-700">连接失败</div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- 添加配置模态框 -->
    <div id="addConfigModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center">
        <div class="bg-white rounded-2xl p-6 max-w-lg w-full mx-4 shadow-2xl max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-bold text-gray-800">添加新配置</h3>
                <button onclick="hideAddConfigModal()" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            </div>
            
            <form id="addConfigForm" class="space-y-4">
                <input type="hidden" id="configId">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">配置名称</label>
                    <input type="text" id="configName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="例如：Web应用项目" required>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">GitLab实例地址</label>
                    <input type="url" id="gitlabUrl" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="https://gitlab.com" required>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">项目名称</label>
                    <input type="text" id="projectName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="username/project-name" required>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">访问令牌</label>
                    <input type="password" id="accessToken" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="输入GitLab个人访问令牌" required>
                    <p class="text-xs text-gray-500 mt-1">在GitLab设置中创建具有read_api和read_repository权限的访问令牌</p>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">描述（可选）</label>
                    <textarea id="description" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="简单描述这个项目..."></textarea>
                </div>
                
                <div class="flex space-x-3 pt-4">
                    <button type="button" onclick="hideAddConfigModal()" class="flex-1 py-2 px-4 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-colors">
                        取消
                    </button>
                    <button type="submit" class="flex-1 btn-primary text-white rounded-lg transition-colors">
                        保存配置
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑配置模态框 -->
    <div id="editConfigModal" class="fixed inset-0 bg-black bg-opacity-50 hidden z-50 flex items-center justify-center">
        <div class="bg-white rounded-2xl p-6 max-w-lg w-full mx-4 shadow-2xl max-h-[90vh] overflow-y-auto">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-xl font-bold text-gray-800">编辑配置</h3>
                <button onclick="hideEditConfigModal()" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                    </svg>
                </button>
            </div>
            
            <form id="editConfigForm" class="space-y-4">
                <input type="hidden" id="editConfigId">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">配置名称</label>
                    <input type="text" id="editConfigName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="例如：Web应用项目" required>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">GitLab实例地址</label>
                    <input type="url" id="editGitlabUrl" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="https://gitlab.com" required>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">项目名称</label>
                    <input type="text" id="editProjectName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="username/project-name" required>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">访问令牌</label>
                    <input type="password" id="editAccessToken" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="输入GitLab个人访问令牌" required>
                    <p class="text-xs text-gray-500 mt-1">在GitLab设置中创建具有read_api和read_repository权限的访问令牌</p>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">描述（可选）</label>
                    <textarea id="editDescription" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="简单描述这个项目..."></textarea>
                </div>
                
                <div class="flex space-x-3 pt-4">
                    <button type="button" onclick="hideEditConfigModal()" class="flex-1 py-2 px-4 bg-gray-100 hover:bg-gray-200 text-gray-700 rounded-lg transition-colors">
                        取消
                    </button>
                    <button type="submit" class="flex-1 btn-primary text-white rounded-lg transition-colors">
                        更新配置
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-gray-800 text-white py-8">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
            <p class="text-gray-400">© 2025 GitLab提交日志分析工具. 基于AI大模型的智能代码分析平台.</p>
        </div>
    </footer>

    <script>
        // 页面加载动画
        document.addEventListener('DOMContentLoaded', function() {
            loadConfigs();
        });

        // 加载配置
        async function loadConfigs() {
            try {
                // 从后端API获取配置数据
                const response = await fetch('/api/configs');
                if (response.ok) {
                    const configs = await response.json();
                    // 转换数据格式以适应现有的渲染逻辑
                    const formattedConfigs = configs.map(config => ({
                        id: config.id,
                        name: config.name,
                        url: config.gitlabUrl,
                        projectName: config.projectName,
                        // 使用默认值，因为数据库中没有这些字段
                        lastSync: '未同步',
                        commits: 0,
                        members: 1,
                        status: config.connectionStatus
                    }));
                    renderConfigs(formattedConfigs);
                    updateStats(formattedConfigs);
                } else {
                    console.error('获取配置失败:', response.status);
                    // 如果获取失败，仍然使用模拟数据
                    useMockData();
                }
            } catch (error) {
                console.error('加载配置失败:', error);
                // 如果出现网络错误，使用模拟数据
                useMockData();
            }
        }

        // 使用模拟数据的函数
        function useMockData() {
            const configs = [
                {
                    id: 1,
                    name: "Web应用项目",
                    url: "gitlab.com/team/webapp",
                    lastSync: "2025-10-29 14:30",
                    commits: 1234,
                    members: 8,
                    status: "connected"
                },
                {
                    id: 2,
                    name: "移动应用开发",
                    url: "gitlab.com/team/mobile",
                    lastSync: "2025-10-28 09:15",
                    commits: 856,
                    members: 5,
                    status: "pending"
                },
                {
                    id: 3,
                    name: "数据分析平台",
                    url: "gitlab.com/team/analytics",
                    lastSync: "2025-10-25 16:45",
                    commits: 432,
                    members: 3,
                    status: "disconnected"
                }
            ];
            
            renderConfigs(configs);
            updateStats(configs);
        }

        // 渲染配置卡片
        function renderConfigs(configs) {
            const configGrid = document.getElementById('configGrid');
            configGrid.innerHTML = '';
            
            configs.forEach(config => {
                const card = document.createElement('div');
                card.className = 'config-card glass-card rounded-2xl p-6 shadow-lg';
                // 根据连接状态确定显示的状态
                console.log(config)
                let status = config.status || 'pending';
                if (config.connectionStatus) {
                    status = config.connectionStatus;
                }
                console.log('status:', status)
                
                card.innerHTML = `
                    <div class="flex justify-between items-start mb-4">
                        <div>
                            <h4 class="text-lg font-bold text-gray-800 mb-1">${config.name}</h4>
                            <p class="text-sm text-gray-500">${config.url || config.gitlabUrl}</p>
                        </div>
                        <div class="${getStatusClass(status)} text-white px-2 py-1 rounded-full text-xs font-medium">
                            ${getStatusText(status)}
                        </div>
                    </div>
                    
                    <div class="space-y-3 mb-4">
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">项目名称:</span>
                            <span class="text-gray-800">${config.projectName || 'N/A'}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">最后同步:</span>
                            <span class="text-gray-800">${config.lastSync || '从未同步'}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">提交总数:</span>
                            <span class="text-gray-800">${config.commits || 0}</span>
                        </div>
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">团队成员:</span>
                            <span class="text-gray-800">${config.members || 1}人</span>
                        </div>
                        ${config.lastTestedAt ? `
                        <div class="flex justify-between text-sm">
                            <span class="text-gray-600">最后测试:</span>
                            <span class="text-gray-800">${new Date(config.lastTestedAt).toLocaleString()}</span>
                        </div>
                        ` : ''}
                    </div>
                    
                    <div class="flex space-x-2">
                        <button onclick="testConfig(${config.id})" class="flex-1 py-2 px-3 bg-blue-50 hover:bg-blue-100 text-blue-700 rounded-lg text-sm transition-colors">
                            测试连接
                        </button>
                        <button onclick="editConfig(${config.id})" class="flex-1 py-2 px-3 bg-gray-50 hover:bg-gray-100 text-gray-700 rounded-lg text-sm transition-colors">
                            编辑
                        </button>
                        <button onclick="deleteConfig(${config.id})" class="py-2 px-3 bg-red-50 hover:bg-red-100 text-red-700 rounded-lg text-sm transition-colors">
                            删除
                        </button>
                    </div>
                `;
                configGrid.appendChild(card);
            });
            
            // 添加动画效果
            anime({
                targets: '.config-card',
                translateY: [50, 0],
                opacity: [0, 1],
                delay: anime.stagger(200),
                duration: 800,
                easing: 'easeOutExpo'
            });
        }

        // 更新统计信息
        function updateStats(configs) {
            document.getElementById('totalCount').textContent = configs.length;
            
            const connected = configs.filter(c => c.status === 'connected').length;
            const pending = configs.filter(c => c.status === 'pending').length;
            const failed = configs.filter(c => c.status === 'disconnected').length;
            
            document.getElementById('connectedCount').textContent = connected;
            document.getElementById('pendingCount').textContent = pending;
            document.getElementById('failedCount').textContent = failed;
        }

        // 获取状态样式类
        function getStatusClass(status) {
            switch(status) {
                case 'connected':
                    return 'status-connected';
                case 'pending':
                case 'untested':
                    return 'status-pending';
                case 'disconnected':
                    return 'status-disconnected';
                default:
                    return 'status-pending';
            }
        }

        // 获取状态文本
        function getStatusText(status) {
            switch(status) {
                case 'connected':
                    return '已连接';
                case 'pending':
                    return '连接中';
                case 'untested':
                    return '待验证';
                case 'disconnected':
                    return '连接失败';
                default:
                    return '未知';
            }
        }

        // 显示添加配置模态框
        function showAddConfigModal() {
            // 清空表单
            document.getElementById('addConfigForm').reset();
            document.getElementById('configId').value = '';
            
            // 恢复默认标题
            document.querySelector('#addConfigModal h3').textContent = '添加新配置';
            
            document.getElementById('addConfigModal').classList.remove('hidden');
            anime({
                targets: '#addConfigModal .bg-white',
                scale: [0.8, 1],
                opacity: [0, 1],
                duration: 300,
                easing: 'easeOutBack'
            });
        }

        // 隐藏添加配置模态框
        function hideAddConfigModal() {
            anime({
                targets: '#addConfigModal .bg-white',
                scale: [1, 0.8],
                opacity: [1, 0],
                duration: 200,
                easing: 'easeInBack',
                complete: function() {
                    document.getElementById('addConfigModal').classList.add('hidden');
                }
            });
        }

        // 测试配置连接
        async function testConfig(configId) {
            const button = event.target;
            const originalText = button.textContent;
            button.textContent = '测试中...';
            button.disabled = true;
            
            try {
                const response = await fetch(`/api/configs/${configId}/test-connection`, {
                    method: 'POST'
                });
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.success) {
                        alert('连接测试成功！配置有效。');
                        // 重新加载配置以更新状态显示
                        loadConfigs();
                    } else {
                        alert('连接测试失败，请检查配置信息。');
                    }
                } else {
                    const error = await response.json();
                    alert('测试连接失败: ' + (error.error || '未知错误'));
                }
            } catch (error) {
                console.error('网络错误:', error);
                alert('网络错误，请稍后重试');
            } finally {
                button.textContent = originalText;
                button.disabled = false;
            }
        }

        // 编辑配置
        async function editConfig(configId) {
            try {
                // 从后端获取配置详情
                const response = await fetch(`/api/configs/${configId}`);
                if (response.ok) {
                    const config = await response.json();
                    
                    // 填充编辑表单
                    document.getElementById('configId').value = config.id;
                    document.getElementById('configName').value = config.name;
                    document.getElementById('gitlabUrl').value = config.gitlabUrl;
                    document.getElementById('projectName').value = config.projectName;
                    document.getElementById('accessToken').value = config.accessToken;
                    document.getElementById('description').value = config.description || '';
                    
                    // 更新模态框标题
                    document.querySelector('#addConfigModal h3').textContent = '编辑配置';
                    
                    // 显示添加配置模态框（用于编辑）
                    showAddConfigModal();
                } else {
                    const error = await response.json();
                    alert('获取配置详情失败: ' + (error.error || '未知错误'));
                }
            } catch (error) {
                console.error('网络错误:', error);
                alert('网络错误，请稍后重试');
            }
        }

        // 显示编辑配置模态框
        function showEditConfigModal() {
            document.getElementById('editConfigModal').classList.remove('hidden');
            anime({
                targets: '#editConfigModal .bg-white',
                scale: [0.8, 1],
                opacity: [0, 1],
                duration: 300,
                easing: 'easeOutBack'
            });
        }

        // 隐藏编辑配置模态框
        function hideEditConfigModal() {
            anime({
                targets: '#editConfigModal .bg-white',
                scale: [1, 0.8],
                opacity: [1, 0],
                duration: 200,
                easing: 'easeInBack',
                complete: function() {
                    document.getElementById('editConfigModal').classList.add('hidden');
                }
            });
        }

        // 删除配置
        async function deleteConfig(configId) {
            if (confirm('确定要删除这个配置吗？此操作不可撤销。')) {
                try {
                    const response = await fetch(`/api/configs/${configId}`, {
                        method: 'DELETE'
                    });
                    
                    if (response.ok) {
                        // 删除成功，移除UI中的卡片
                        const card = event.target.closest('.config-card');
                        anime({
                            targets: card,
                            scale: [1, 0],
                            opacity: [1, 0],
                            duration: 300,
                            easing: 'easeInBack',
                            complete: function() {
                                card.remove();
                                // 重新加载配置以更新统计数据
                                loadConfigs();
                            }
                        });
                        alert('配置删除成功！');
                    } else {
                        const error = await response.json();
                        alert('删除配置失败: ' + (error.error || '未知错误'));
                    }
                } catch (error) {
                    console.error('网络错误:', error);
                    alert('网络错误，请稍后重试');
                }
            }
        }

        // 添加配置表单提交
        document.getElementById('addConfigForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const configId = document.getElementById('configId').value;
            const formData = {
                name: document.getElementById('configName').value,
                gitlabUrl: document.getElementById('gitlabUrl').value,
                projectName: document.getElementById('projectName').value,
                accessToken: document.getElementById('accessToken').value,
                description: document.getElementById('description').value
            };
            
            // 模拟保存过程
            const submitBtn = e.target.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = '保存中...';
            submitBtn.disabled = true;
            
            try {
                let response;
                if (configId) {
                    // 更新现有配置
                    response = await fetch(`/api/configs/${configId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(formData)
                    });
                } else {
                    // 创建新配置
                    response = await fetch('/api/configs', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(formData)
                    });
                }
                
                if (response.ok) {
                    const result = await response.json();
                    console.log(configId ? '配置更新成功:' : '配置保存成功:', result);
                    alert(configId ? '配置更新成功！' : '配置保存成功！');
                    hideAddConfigModal();
                    e.target.reset();
                    document.getElementById('configId').value = ''; // 清空隐藏的ID字段
                    loadConfigs(); // 重新加载配置
                } else {
                    const error = await response.json();
                    console.error(configId ? '更新配置失败:' : '保存配置失败:', error);
                    alert(configId ? '更新配置失败: ' : '保存配置失败: ' + (error.error || '未知错误'));
                }
            } catch (error) {
                console.error('网络错误:', error);
                alert('网络错误，请稍后重试');
            } finally {
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            }
        });

        // 更新配置表单提交
        document.getElementById('editConfigForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const configId = document.getElementById('editConfigId').value;
            const formData = {
                name: document.getElementById('editConfigName').value,
                gitlabUrl: document.getElementById('editGitlabUrl').value,
                projectName: document.getElementById('editProjectName').value,
                accessToken: document.getElementById('editAccessToken').value,
                description: document.getElementById('editDescription').value
            };
            
            const submitBtn = e.target.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            submitBtn.textContent = '更新中...';
            submitBtn.disabled = true;
            
            try {
                // 发送更新请求到后端API
                const response = await fetch(`/api/configs/${configId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                
                if (response.ok) {
                    const result = await response.json();
                    console.log('配置更新成功:', result);
                    alert('配置更新成功！');
                    hideEditConfigModal();
                    loadConfigs(); // 重新加载配置
                } else {
                    const error = await response.json();
                    console.error('更新配置失败:', error);
                    alert('更新配置失败: ' + (error.error || '未知错误'));
                }
            } catch (error) {
                console.error('网络错误:', error);
                alert('网络错误，请稍后重试');
            } finally {
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            }
        });
    </script>
</body>
</html>